const express = require('express');
const userModel = require('../db/models/userModel')
const STATUSCODE = require('../utils/constants')

const formidable = require('formidable');
const {resolve} = require('path');
const md5 = require('md5');

const router = express.Router();

// 创建解析对象
let readForm =new formidable.IncomingForm({
    uploadDir:resolve(__dirname,'../public/upload'),
    keepExtensions:true,
    maxFieldsSize:1024*1024
})

// 获取用户分页列表
router.get('/:page/:limit',async (req,res)=>{

    let {page,limit} = req.params;

    // console.log(isNaN(Number(page)));
    // console.log(page,limit);
    if( !isNaN(Number(page)) ){
        let pageNow = (page - 1) * limit;
       try{
        let data = await userModel.find().skip(pageNow).limit(limit);
        let count = await userModel.countDocuments();
        res.json({
            code:STATUSCODE.SUCCESS,
            message:"获取成功",
            data:{
                users:data,
                total:count
            }
        })
       }catch(err){
          res.json({
              code:STATUSCODE.SERVERERROR,
              message:"服务器错误"
          })
       }
    }else{
        res.json({
            code:STATUSCODE.DATAERROR,
            message:"参数错误"
        })
    }
})

// 添加用户接口
router.post('/',(req,res)=>{
    readForm.parse(req,async (err,fields,files)=>{
        if(err){
            res.json({
                code:STATUSCODE.DATAERROR,
                message:"上传失败，参数不正确"
            })
        }else{
            //上传成功
            let {username,pwd} =fields;
            // 判断用户是否已存在
            let user = await userModel.findOne({username})
            if(user){
               return res.json({
                    code:STATUSCODE.DATAERROR,
                    message:"用户名已存在"
                })
            }
            let {profile} = files;
            let [PersistentFile] = profile
            let imgUrl = '/upload/'+ PersistentFile.newFilename;
            let data = await userModel.create({
                username:username.toString(),
                pwd:md5(pwd.toString()),
                profile:imgUrl
            })
            res.json({
                code:STATUSCODE.SUCCESS,
                message:"添加用户成功",
                data
            })
        }
    })
})

// 获取用户信息
router.get('/',async (req,res)=>{
    // 通过id ？ query
    let {id} = req.query;
    let data = await userModel.findById(id)
    res.json({
        code:STATUSCODE.SUCCESS,
        message:"获取用户信息成功",
        data
    })
})

// 更新用户信息
router.put('/',(req,res)=>{

    readForm.parse(req,async (err,fields,files)=>{

        // 获取对应数据 _id,username
        let {_id,username} = fields;
        let {profile} = files;
        let [PersistentFile] = profile
        let imgUrl = '/upload/'+ PersistentFile.newFilename;
        // 判断用户是否已存在
        let user = await userModel.findOne({username})
        if(user){
           return res.json({
                code:STATUSCODE.DATAERROR,
                message:"用户名已存在"
            })
        }
        try{
            let user =await userModel.updateOne({_id},{
                username:username.toString(),
                profile:imgUrl
            });
            res.json({
                code:STATUSCODE.SUCCESS,
                message:"更新用户成功"
            })
        }catch(err){
            res.json({
                code:STATUSCODE.SERVERERROR,
                message:"服务器错误"
            })
        }
    })
})

// 删除用户
router.delete('/:id',async(req,res)=>{
    let {id} = req.params;

    await userModel.deleteOne({_id:id});

    res.json({
        code:STATUSCODE.SUCCESS,
        message:"删除用户成功"
    })

})

module.exports = router;